import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserVO } from '../vo/UserVO';
import { ApiUrl } from '../api/ApiUrl';
import { ApiService } from '../api/api.service';
import { VisitVO } from '../vo/VisitVO';
@Component({
  selector: 'app-visit',
  templateUrl: './visit.page.html',
  styleUrls: ['./visit.page.scss'],
})
export class VisitPage implements OnInit {
  userItem: UserVO;
  items: VisitVO[] = [];
  iconsultantid: number;
  constructor(public api: ApiService, private router: Router) { }

  ngOnInit() {
    this.userItem = ApiUrl.user;
    if (this.userItem == null) {
        this.iconsultantid = 0;
    } else {
      this.iconsultantid = this.userItem.iconsultantid;
    }
    this.doDownRefresh(null);
  }
  goToAdd() {
    this.router.navigate(['/addvisit']);
}
 // 下拉刷型界面
 doDownRefresh(evt) {
  if (evt === null) {
    this.onSearch('0', evt);
  } else {
    console.log('iid:' + this.items[0].iid);
    this.onSearch(this.items[0].iid, evt);
  }
}
onSearch(iid: string = '0', evt: any, opt: string = 'down') {
  this.api.getItems<VisitVO>(ApiUrl.findVisit, { 'iid': iid, 'option': opt, 'iorgname': this.userItem.iorgname }).subscribe(response => {
    if (evt) {
      evt.target.complete();
    }
    if (response === null || response.length === 0) {
      console.log('没有数据返回');
      return;
    }
    console.log(opt);
    console.log(response);
    if (opt === 'down') { // 下拉刷新，把items追加到新的数据的尾部
      // this.items = this.items.concat(response);
      this.items = response.concat(this.items);
    } else {
      this.items = this.items.concat(response);
      // this.items = this.items.splice(0, 0, response);
    }
  }, () => {
    if (evt) {
      evt.target.complete();
    }
    console.log('出错了');
  });
}
doUpRefresh(evt) {
  console.log('上拉刷新');
  this.onSearch(this.items[this.items.length - 1].iid, evt, 'up');
}

goToDetails(iid) {
  this.router.navigate(['/visitdetail', {'iid': iid}]);
}
}
